package controller;

import java.io.IOException;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.PersistenceContext;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.*;

/**
 * Servlet implementation class SignInServlet
 */
@WebServlet("/SignInServlet")
public class SignInServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	
	//EntityManagerFactory emf;
	
	
	@PersistenceContext
	EntityManager em;
	

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public SignInServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	//public void init() {

	//	emf = Persistence.createEntityManagerFactory("Day7JSPLogIn");
	//	em = emf.createEntityManager();

	//}
	
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		
		System.out.println(username);
		System.out.println(password);
		ServletContext con = request.getServletContext();
		
		List<User> users = em.createQuery("select u from User u", User.class).getResultList();
		
		if(request.getParameter("login")!=null)
		{
			for(User temp:users)
			{
				if(temp.getUsername().equals(username) && temp.getPassword().equals(password))
				{
					RequestDispatcher rd = con.getRequestDispatcher("/successful.jsp");
					rd.forward(request, response);
				}
			}
			
			request.setAttribute("failLogin", 1);
			RequestDispatcher rd = con.getRequestDispatcher("/loginPage.jsp");
			rd.forward(request, response);
		}
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}